package org.suburban.servlet.staticdata;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.WARNING;
import java.io.IOException;
import java.io.StringReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.suburban.servlet.XMPPServlet;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


/**
 * class to update info about all directions
 * @author Alexey Palamarchuk (slonnik@gmail.com)
 *
 */
@SuppressWarnings("serial")
public class DirectionsServlet extends XMPPServlet{
	
	/** HTTP query template */
	private static final String template = "http://m.rasp.yandex.ru/direction";
			
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		/** query for data*/
		String data = fetchURL(template, "UTF-8");
		int start = data.indexOf("<ul");
		int end = data.indexOf("</ul", start);
		data = data.substring(start, end) + "</ul>";
		
		logger.log(FINE, "Directions data: {0}", data);
		/** parse data */
		try
		{
			SAXParserFactory factory = SAXParserFactory.newInstance();
	        factory.newSAXParser().parse(new InputSource(new StringReader(data)),
	        		new DirectionsCracker());
		}
		catch(ParserConfigurationException ex)
		{
			logger.log(WARNING,"Failed to parse HTML response: {}", ex.getMessage());
			return;
		}
		catch(SAXException ex)
		{
			logger.log(WARNING,"Failed to parse HTML response: {}", ex.getMessage());
			return;
		}
	}
	
}
